<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button type="primary" round @click="addRoles()">添加用户</el-button>
      </div>

      <el-table :data="rolesList" stripe style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom',index1==0?'bdtop':'','vcenter']"
              v-for="(item1,index1) in scope.row.children"
              :key="index1"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRights(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级、三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[index2===0?'':'bdtop','vcenter']"
                  v-for="(item2,index2) in item1.children"
                  :key="index2"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRights(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3,index3) in item2.children"
                      :key="index3"
                      closable
                      @close="removeRights(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="getEditRoles(scope.row.id)"
              size="mini"
              round
              class="r_m_btns"
            >编辑</el-button>

            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteRoles(scope.row.id)"
              round
              class="r_m_btns"
            >删除</el-button>

            <el-button
              @click="showSetRightsDialog(scope.row)"
              type="success"
              icon="el-icon-setting"
              size="mini"
              round
              class="r_m_btns"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限 -->
    <el-dialog
      @close="setRightsDialogClose"
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="30%"
    >
      <!-- 分配权限树型控件 -->
      <el-tree
        ref="setRightsTree"
        show-checkbox
        node-key="id"
        :data="rightsList"
        :props="treeProps"
        :default-checked-keys="defKeys"
        default-expand-all
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色 -->
    <el-dialog title="添加角色" :visible.sync="addRolesDialogVisible" width="30%" center>
      <el-form ref="addRolesRef" :rules="addRolesRules" :model="addRolesForm" label-width="100px">
        <el-form-item label="角色名称：" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述：" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddRolesForm()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色 -->
    <el-dialog title="编辑角色" :visible.sync="editRolesDialogVisible" width="30%" center>
      <el-form
        ref="editRolesRef"
        :rules="editRolesRules"
        :model="editRolesForm"
        label-width="100px"
      >
        <el-form-item label="角色名称：" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述：" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditRolesForm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      setRightsDialogVisible: false,
      rightsList: [],
      treeProps: {
        children: "children",
        label: "authName"
      },
      defKeys: [],
      // 即将分配权限的角色id
      roleId: "",
      //添加角色对话框
      addRolesDialogVisible: false,
      //添加角色获取的表单数据
      addRolesForm: {},
      // 添加角色的规则
      addRolesRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" }
        ]
      },
      // 编辑角色对话框
      editRolesDialogVisible: false,
      // 编辑角色获取的表单数据
      editRolesForm: {},
      // 编辑角色的规则
      editRolesRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" }
        ]
      }
    };
  },

  created() {
    this.getRolesList();
  },

  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) return this.$message.error("加载失败");
      this.rolesList = res.data;
    },
    //添加角色
    addRoles() {
      this.addRolesDialogVisible = true;
    },
    // 按下确认按钮提交添加角色表单
    submitAddRolesForm() {
      this.$refs.addRolesRef.validate(async valid => {
        if (!valid) return false;
        const { data: res } = await this.$http.post(`roles`, this.addRolesForm);
        console.log(res);

        if (res.meta.status !== 201) return this.$message.error("角色添加失败");
        this.$message.success("角色添加成功");
        this.$refs.addRolesRef.resetFields();
      });
      this.addRolesDialogVisible = false;
      this.getRolesList();
    },
    // 删除权限
    async removeRights(role, id) {
      const confirmResult = await this.$confirm("是否确定删除改权限?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(err => err);
      if (confirmResult !== "confirm") return this.$message.info("取消删除");
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${id}`
      );
      if (res.meta.status != 200) return this.$message.error("删除失败");
      this.$message.success("删除成功");
      role.children = res.data;
    },
    // 分配权限列表
    async showSetRightsDialog(role) {
      this.roleId = role.id;
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) return this.$message.error("加载失败");
      this.rightsList = res.data;
      this.getCheckedId(role, this.defKeys);
      this.setRightsDialogVisible = true;
    },
    // 获取选中权限的id
    getCheckedId(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach(item => {
        this.getCheckedId(item, arr);
      });
    },
    //关闭分配权限对话框
    setRightsDialogClose() {
      this.defKeys = [];
    },
    // 确定设置权限
    async changeRights() {
      const keys = [
        ...this.$refs.setRightsTree.getCheckedKeys(),
        ...this.$refs.setRightsTree.getHalfCheckedKeys()
      ];
      const idStr = keys.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      );
      if (res.meta.status != 200) return this.$message.error("分配权限失败");
      this.$message.success("分配权限成功");
      this.getRolesList();
      this.setRightsDialogVisible = false;
    },
    // 查询要编辑角色
    async getEditRoles(id) {
      const { data: res } = await this.$http.get(`roles/${id}`);
      console.log(res);
      this.editRolesForm = res.data;
      this.editRolesDialogVisible = true;
    },
    // 按下确认按钮提交编辑角色表单
    submitEditRolesForm() {
      this.$refs.editRolesRef.validate(async valid => {
        if (!valid) return false;
        const { data: res } = await this.$http.put(
          `roles/${this.editRolesForm.roleId}`,
          this.editRolesForm
        );
        if (res.meta.status !== 200) return this.$message.error("角色修改失败");
        this.$message.success("角色修改成功");
      });
      this.editRolesDialogVisible = false;
      this.getRolesList();
    },
    // 删除角色
    deleteRoles(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${id}`);
          if (res.meta.status !== 200) return this.$message.error("删除失败");
          this.$message.success("删除成功");
          this.getRolesList();
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    }
  }
};
</script>

<style scoped lang='less'>
.el-breadcrumb {
  margin-bottom: 20px;
  padding: 15px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
